<!-- components/nfc-reader/nfc-reader.vue -->
<template>
  <view class="nfc-popup" v-if="show">
    <view class="nfc-mask" @click="handleClose"></view>
    <view class="nfc-content">
      <view class="nfc-title">NFC读取</view>
      <view class="nfc-status">{{ nfcStatus }}</view>
      <view class="nfc-data">{{ nfcData }}</view>
      <view class="nfc-icon" :class="{ scanning: isScanning }">
        <view class="nfc-wave"></view>
        <view class="nfc-symbol">N</view>
      </view>
      <view class="nfc-buttons">
        <button type="default" class="btn-cancel" @click="handleClose">取消</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue';

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['success', 'error', 'update:show']);

const nfcStatus = ref('准备读取...');
const nfcData = ref('');
const isScanning = ref(false);
let nfcAdapter = null;

// 监听show变化
watch(() => props.show, (newVal) => {
  if (newVal) {
    startNFCReading();
  } else {
    stopNFCReading();
  }
});

// 关闭弹窗
const handleClose = () => {
  emit('update:show', false);
};

// 开始NFC读取
const startNFCReading = () => {
  try {
    nfcStatus.value = '正在初始化NFC...';
    isScanning.value = true;

    // 获取系统信息
    // 获取NFC适配器
    nfcAdapter = wx.getNFCAdapter();

    // 开始搜索
    nfcAdapter.startDiscovery({
      success: () => {
        nfcStatus.value = '请将NFC标签靠近手机背面';
        // 监听NFC发现事件
        nfcAdapter.onDiscovered(handleNFCDiscovered);
      },
      fail: (error) => {
        handleError('NFC搜索启动失败');
        console.error('启动NFC搜索失败:', error);
      }
    });
  } catch (error) {
    handleError('NFC初始化失败');
    console.error('NFC初始化失败:', error);
  }
};

// 处理NFC读取结果
const handleNFCDiscovered = (res) => {
  try {
    // 获取ID
    const id = Array.from(res.id)
      .map(byte => byte.toString(16).padStart(2, '0'))
      .join('');

    // 读取NDEF消息
    const nfcData = {
      id: id,
      messages: []
    };

    if (res.messages && res.messages.length > 0) {
      res.messages.forEach(message => {
        message.records.forEach(record => {
          const payload = String.fromCharCode.apply(null, record.payload.slice(1));
          nfcData.messages.push({
            type: String.fromCharCode.apply(null, record.type),
            payload: payload
          });
        });
      });
    }

    nfcStatus.value = '读取成功';
    nfcData.value = JSON.stringify(nfcData);
    emit('success', nfcData);

    // 读取成功后延迟关闭
    setTimeout(() => {
      emit('update:show', false);
    }, 1000);

  } catch (error) {
    handleError('解析NFC数据失败');
    console.error('解析NFC数据失败:', error);
  }
};

// 停止NFC读取
const stopNFCReading = () => {
  isScanning.value = false;
  if (nfcAdapter) {
    try {
      nfcAdapter.stopDiscovery();
      nfcAdapter.offDiscovered(handleNFCDiscovered);
    } catch (error) {
      console.error('停止NFC搜索失败:', error);
    }
    nfcAdapter = null;
  }
};

// 处理错误
const handleError = (message) => {
  nfcStatus.value = message;
  isScanning.value = false;
  emit('error', message);
};
</script>

<style scoped>
.nfc-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nfc-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
}

.nfc-content {
  position: relative;
  background-color: #fff;
  border-radius: 16px;
  padding: 24px;
  width: 280px;
  z-index: 1000;
}

.nfc-title {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 16px;
}

.nfc-status {
  text-align: center;
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
}

.nfc-icon {
  position: relative;
  width: 120px;
  height: 120px;
  margin: 0 auto 24px;
}

.nfc-symbol {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50px;
  height: 50px;
  background-color: #007AFF;
  border-radius: 12px;
  color: white;
  font-size: 24px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nfc-wave {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
  border: 3px solid #007AFF;
  border-radius: 24px;
  opacity: 0;
}

.scanning .nfc-wave {
  animation: wave 2s infinite;
}

@keyframes wave {
  0% {
    transform: translate(-50%, -50%) scale(0.8);
    opacity: 1;
  }

  100% {
    transform: translate(-50%, -50%) scale(1.5);
    opacity: 0;
  }
}

.nfc-buttons {
  display: flex;
  justify-content: center;
}

.btn-cancel {
  width: 120px;
  height: 40px;
  line-height: 40px;
  font-size: 16px;
  color: #666;
  background: #f5f5f5;
  border: none;
}
</style>